//
//  ActivityWidgetUtil.swift
//  TomatoClock
//
//  Created by DaleGuo on 2023/11/9.
//

import ActivityKit
import Foundation

class ActivityWidgetUtil {
    // 全局用一个activity
    static var acticity: Activity<CountDonwAttributes>?
    
//    let tomatoDate: Date
    
//    init(tomatoDate: Date) {
//        self.tomatoDate = tomatoDate
//    }
    
    // 为了liveActivity
    static func startActivity(tomatoDate : Date) {
        let attributes = CountDonwAttributes(timerName: "ClockTomato 🍅")
        let state = CountDonwAttributes.TimerStatus(endTime: tomatoDate, startTime: .now)
        
        // staleDate 过期时间
        let content = ActivityContent(state: state, staleDate: Calendar.current.date(byAdding: .second, value: 5, to: tomatoDate))
        

        
        
        do {
            ActivityWidgetUtil.acticity = try Activity<CountDonwAttributes>.request(attributes: attributes, content: content, pushType: nil)
        } catch {
            print(error.localizedDescription)
        }
        
        
        Task {
            await ActivityWidgetUtil.acticity?.end(content, dismissalPolicy: .after(Calendar.current.date(byAdding: .second, value: 5, to: tomatoDate)!))
        }
        
    }

    static func stopActivity() {
        let state = CountDonwAttributes.TimerStatus(endTime: .now, startTime: .now)
        let content = ActivityContent(state: state, staleDate: .now)
        
        Task {
            await ActivityWidgetUtil.acticity?.end(content, dismissalPolicy: .immediate)
        }
    }
}
